<template>
  <div class="category-view">
    <el-card>
      <el-dialog
        title="tips"
        :visible.sync="dialogVisible"
        width="60%"
        height="500px"
        :before-close="beforeClose"
      >
        <category-edit
          v-bind.sync="editCate"
          @submit="submit"
          @clear="clearEdit"
          @cancel="cancel"
        >
        </category-edit>
      </el-dialog>
      <div class="title-box">
        <el-button
          type="primary"
          @click="(dialogVisible = true), (isEdit = false)"
        >
          新建商品分类
        </el-button>

        <div class="search-box">
          <el-icon class="el-icon-search"></el-icon>
          <el-input
            v-model="keywords"
            clearable
            placeholder="请输入商品名称"
          ></el-input>
        </div>
      </div>

      <el-table
        style="margin-top: 10px"
        :data="filterTreeCategory(keywords)"
        border
        height="550px"
        row-key="id"
        lazy
        :load="load"
        :tree-props="{ hasChildren: 'has_children' }"
        ref="table"
      >
        <el-table-column prop="id" label="编号"> </el-table-column>
        <el-table-column prop="name" label="类别名称"> </el-table-column>
        <el-table-column prop="banner_image_alt" label="类别图">
          <template v-slot="{ row: { banner_image_alt } }">
            <el-image
              style="width: 60px; height: 60px"
              :src="banner_image_alt"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="类别层级">
          <template v-slot="{ row: { level } }">
            <span v-if="level === 0">
              <el-tag type="success">一级分类 </el-tag>
            </span>
            <span v-else-if="level === 1">
              <el-tag type="warning">二级分类</el-tag>
            </span>
            <span v-else-if="level === 2">
              <el-tag type="danger">三级分类</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="sort_order" label="显示顺序"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-link
              :underline="false"
              style="color: blue"
              @click="onEdit(row)"
            >
              <i class="el-icon-edit"></i> 编辑
            </el-link>
            <el-link
              :underline="false"
              style="margin-left: 10px; color: red"
              @click="onDelete(row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
import CategoryEdit from "./CategoryEdit";
import * as types from "../../../store/types";
import { treeFind } from "../../../utils/tree";

// Map： ES6新的数据结构：就像是对象，也是一种键值对的方式 键是唯一的 要求：他的key除了是字符串，还可以是任意数据
// Map 没有响应式效果
const nodeMap = new Map();
export default {
  name: "CategoryView",
  components: { CategoryEdit },
  computed: {
    ...mapGetters(["treeCategory", "filterTreeCategory"]),
  },
  data() {
    return {
      keywords: "",
      isEdit: false,
      dialogVisible: false,
      editCate: {
        id: undefined,
        name: "",
        sort_order: 0,
        parent: undefined,
        banner_image_alt: "",
      },
    };
  },
  methods: {
    ...mapActions([
      types.EDIT_CATEGORY,
      types.SET_CATEGORY,
      types.ADD_CATEGORY,
      types.DELETE_CATEGORY,
    ]),
    // 重新加载父节点下的子节点的数据
    reload(id) {
      if (!id) return;
      // console.log(id);
      // console.log(...nodeMap.entries());
      const { resolve } = nodeMap.get(Number(id));
      this.$set(this.$refs.table.store.states.lazyTreeNodeMap, id, []);
      const parentNode = treeFind(this.treeCategory, (node) => node.id === id);
      resolve(parentNode.children ? parentNode.children : []);
    },
    async submit(data) {
      if (this.isEdit) {
        //isEdit 为true 就是 更新  反之就是创建
        const result = await this[types.EDIT_CATEGORY](data);
        // console.log('000',result)
        this.reload(result.parent);
        this.$message.success("更新成功");
      } else {
        const result = await this[types.ADD_CATEGORY](data);
        this.reload(result.parent);
      }

      this.dialogVisible = false;
      this.clearEdit();
      this.isEdit = false;
    },
    //  取消创建框操作
    cancel() {
      this.dialogVisible = false;
    },
    clearEdit() {
      this.isEdit = false;
      this.editCate = {
        id: undefined,
        name: "",
        sort_order: 0,
        parent: undefined,
        image: undefined, // 图片的id
        banner_image_alt: "",
      };
    },
    onEdit(data) {
      // console.log(data);
      this.editCate = { ...this.editCate, ...data };
      this.dialogVisible = true;
      this.isEdit = true;
    },
    //  删除操作
    async onDelete(data) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定？三思而行！！！",
        cancelButtonText: "取消！！！！",
        type: "warning",
      })
        .then(async () => {
          const result = await this[types.DELETE_CATEGORY](data);
          this.reload(result.parent);
          // this.$message({ type: "success", message: "删除成功!" });
        })
        .catch((err) => {
          // this.$message({ type: "info", message: "已取消删除" });
          return Promise.reject(err);
        });
    },
    load(tree, treeNode, resolve) {
      // console.log("tree", tree); //当前第一级的数据
      // console.log("treeNode", treeNode); // 第一级下面的数据
      // console.log(this.$refs.table.store.states);
      // 用户每次点击父节点时，就把 懒加载相关的一些数据和方法，记录下来
      nodeMap.set(tree.id, { treeNode, resolve });

      setTimeout(() => {
        resolve(tree.children);
      }, 100);
    },
    beforeClose(done) {
      this.clearEdit();
      done();
    },
  },
};
</script>

<style lang="scss" scoped>
.el-card {
  ::v-deep.el-card__body {
    padding: 0;
  }
}
.title-box {
  /*background-color: blue;*/
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .search-box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    height: 32px;
    /*margin-top: 26px;*/
    margin-right: 20px;

    .el-input {
      margin-left: 12px;
      width: 210px;
      ::v-deep.el-input__inner {
        border: none;
        border-bottom: 2px solid #d9d9d9;
      }
    }
  }
}
</style>
